/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007-2008 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.spring.transaction.bean.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.UnexpectedRollbackException;

import com.genia.toolbox.basics.exception.technical.TechnicalException;
import com.genia.toolbox.spring.transaction.bean.EnlistableResource;

/**
 * an {@link EnlistableResource} that aggregate several
 * {@link EnlistableResource}.
 */
public class EnlistableResourceAggregator
    implements EnlistableResource
{

  /**
   * the <code>Log</code> variabe.
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(EnlistableResourceAggregator.class);

  /**
   * the resources to aggregate.
   */
  private List<? extends EnlistableResource> resources;



  /**
   * constructor.
   * 
   * @param enlistableResources
   *          the resources to aggregate
   */
  public EnlistableResourceAggregator(EnlistableResource... enlistableResources)
  {
    resources = Arrays.asList(enlistableResources);
  }



  /**
   * commit the transaction defined by {@link TransactionStatus}. A
   * {@link #prepare(TransactionStatus)} must have been called.
   * 
   * @param status
   *          the {@link TransactionStatus} of the transaction
   * @throws TechnicalException
   *           if an error occured
   * @see com.genia.toolbox.basics.transaction.bean.EnlistableResource#commit(org.springframework.transaction.TransactionStatus)
   */
  public void commit(TransactionStatus status)
      throws TechnicalException
  {
    Exception hasFailed = null;
    for (EnlistableResource resource : resources) {
      try {
        if (hasFailed == null) {
          resource.commit(status);
        }
        else {
          resource.rollback(status);
        }
      }
      catch (Exception e) {
        if (hasFailed == null) {
          hasFailed = e;
        }
      }
    }
    if (hasFailed != null) {
      throw new TechnicalException(new TransactionSystemException(
          "An enlisted resource succeded in its prepare statement, but failed in its commit statement. The state of the application might be incoherent.", hasFailed));
    }
  }



  /**
   * getter for the resources property.
   * 
   * @return the resources
   */
  public List<? extends EnlistableResource> getResources()
  {
    return resources;
  }



  /**
   * prepare the transaction defined by {@link TransactionStatus}. If this
   * method succeed, a {@link #commit(TransactionStatus)} must succeed or the
   * transactional integrity of the application won't be insured.
   * 
   * @param status
   *          the {@link TransactionStatus} of the transaction
   * @throws TechnicalException
   *           if an error occured
   * @see com.genia.toolbox.basics.transaction.bean.EnlistableResource#prepare(org.springframework.transaction.TransactionStatus)
   */
  public void prepare(TransactionStatus status)
      throws TechnicalException
  {
    List<EnlistableResource> preparedResources = new ArrayList<EnlistableResource>();
    try {
      for (EnlistableResource resource : resources) {
        resource.prepare(status);
        preparedResources.add(resource);
      }
    }
    catch (Exception e) {
      try {
        rollbackTransactions(status, preparedResources);
      }
      catch (Exception rollbackException) {
        LOGGER.warn(rollbackException.getMessage(), rollbackException);
      }
      throw new TechnicalException(new UnexpectedRollbackException("One of the enlisted resource failed to prepare for commiting a transaction", e));
    }
  }



  /**
   * rollback the transaction defined by {@link TransactionStatus}.
   * 
   * @param status
   *          the {@link TransactionStatus} of the transaction
   * @throws TechnicalException
   *           if an error occured
   * @see com.genia.toolbox.basics.transaction.bean.EnlistableResource#rollback(org.springframework.transaction.TransactionStatus)
   */
  public void rollback(TransactionStatus status)
      throws TechnicalException
  {
    rollbackTransactions(status, resources);
  }



  /**
   * setter for the resources property.
   * 
   * @param resources
   *          the resources to set
   */
  public void setResources(List<? extends EnlistableResource> resources)
  {
    this.resources = resources;
  }



  /**
   * start a new transaction for the current object.
   * 
   * @param definition
   *          {@link TransactionDefinition} instance (can be <code>null</code>
   *          for defaults), describing propagation behavior, isolation level,
   *          timeout etc
   * @param status
   *          the {@link TransactionStatus} of the transaction
   * @throws TechnicalException
   *           if an error occured
   * @see com.genia.toolbox.basics.transaction.bean.EnlistableResource#startTransaction(org.springframework.transaction.TransactionDefinition,
   *      org.springframework.transaction.TransactionStatus)
   */
  public void startTransaction(TransactionDefinition definition, TransactionStatus status)
      throws TechnicalException
  {
    List<EnlistableResource> enlistedResources = new ArrayList<EnlistableResource>();
    try {
      for (EnlistableResource resource : resources) {
        resource.startTransaction(definition, status);
        enlistedResources.add(resource);
      }
    }
    catch (Exception e) {
      try {
        rollbackTransactions(status, enlistedResources);
      }
      catch (Exception rollbackException) {
        LOGGER.warn(rollbackException.getMessage(), rollbackException);
      }
      throw new TechnicalException(new CannotCreateTransactionException("One of the enlisted resource failed to open a transaction", e));
    }
  }



  /**
   * call the rollback method on the {@link EnlistableResource} given in
   * parameter, catching silentiously any exception.
   * 
   * @param status
   *          the {@link TransactionStatus} of the transaction to rollback
   * @param enlistedResources
   *          the {@link EnlistableResource}s to rollback
   * @throws TechnicalException
   *           if an error occured
   */
  private void rollbackTransactions(TransactionStatus status, List<? extends EnlistableResource> enlistedResources)
      throws TechnicalException
  {
    Exception error = null;
    for (EnlistableResource resource : enlistedResources) {
      try {
        resource.rollback(status);
      }
      catch (Exception rollbackException) {
        if (error == null) {
          error = rollbackException;
        }
        else {
          LOGGER.warn(rollbackException.getMessage(), rollbackException);
        }
      }
    }
    if (error != null) {
      if (error instanceof TechnicalException) {
        throw (TechnicalException) error;
      }
      throw new TechnicalException(error);
    }
  }
}
